//
//  GameScene.m
//  menuTutorial
//
//  Created by Greg Dunn on 9/7/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SSGameScene.h"
#import "SSGame.h"
#import "SSStorage.h"
#import "SSHighScoreScene.h"
#import "SSLevel.h"
#import "SSLevelSelectScene.h"
#import "SSMenuScene.h"

@implementation SSGameScene

@synthesize currentLevelIndex, game, currentLevel, currentGameScore, currentLivesLeft, gameHighScore;

@synthesize dataManager;

- (id) init
{
	self = [super init];
	if (self != nil) {
		CMLog(@"GameScene->init");
		
		self.currentLevelIndex = [SSStorage getCurrentLevelIndex];
	    self.currentGameScore = [SSStorage getCurrentGameScore];
		self.currentLivesLeft = [SSStorage getCurrentLivesLeft];
		
		
		dataManager = [SSDataManager sharedManager];
//		dataManager.currentlevel = 0;
		dataManager.score = 0;
		dataManager.misses = 1;
		
		//On load - check for lives left
		 if ([self currentLivesLeft]  > 0 )
		 {	 
			 CMLog(@"GameScene->init->currentLivesLeft>0 : %i", [self currentLivesLeft]);		 
			 [self loadLevel:[self currentLevelIndex]];
			 [self startLevel];
		 } else { 
			  CMLog(@"GameScene->init->currentLivesLeft<0 : %i, GameOver", [self currentLivesLeft]);
			 [self onGameOver];
		 }
		
		//[self onMenu];
	}
	return self;
}

- (void)loadLevel:(int)value{
	CMLog(@"GameScene->loadLevel: %i", value);
	
	currentLevel = [[dataManager levels] objectAtIndex:value - 1];
	CMLog(@"currentLevel.background : %@", currentLevel.background);
};

- (void)loadNextLevel{
	[SSStorage setCurrentLevelIndex:([SSStorage getCurrentLevelIndex] + 1)];
	[self loadLevel:[SSStorage getCurrentLevelIndex]];
};

- (void)startLevel{	
	CMLog(@"GameScene->startLevel");
	self.game = [[SSGame alloc] initWithLevel:[self currentLevel] atScore:[self currentGameScore] withLivesLeft:[self currentLivesLeft]];
	[self addChild:self.game];	
}

- (void)onGameOver
{
	[self onGameEnd];
};

- (void)onGameEnd
{
	[self setGameHighScore:[[SSStorage getUserValueForKey:@"gameHighScore" withDefault:@"0"] intValue]];
	
	if ([self currentGameScore] > [self gameHighScore])
	{
		[self onHighScore];
	} else {
		[self onMenu];
	}	
};

- (void)onLevelSelect
{
	[[CCDirector sharedDirector] replaceScene:[SSLevelSelectScene node]];
}

- (void)onHighScore
{
	CMLog(@"on high scores");
	[[CCDirector sharedDirector] replaceScene:[SSHighScoreScene node]];
}

- (void)onMenu
{
	CMLog(@"on menu scene");
	[[CCDirector sharedDirector] replaceScene:[SSMenuScene node]];
}
@end
